import type { ConfigEnv } from 'vite'
import { resolve } from 'node:path'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import { createViteProxy } from './build/config'
import { vitPlugins } from './build/plugins'
import { convertEnv } from './build/utils'

export default defineConfig(({ command, mode }: ConfigEnv) => {
  const viteEnv = convertEnv(loadEnv(mode, resolve(__dirname, 'env')))
  console.log('viteEnv =>', viteEnv)
  const isBuild = command === 'build'
  return {
    base: '',
    resolve: {
      alias: {
        '~': fileURLToPath(new URL('./', import.meta.url)),
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    envDir: fileURLToPath(new URL('./env', import.meta.url)),
    server: {
      port: 7788,
      host: true,
      proxy: createViteProxy(viteEnv),
    },
    plugins: vitPlugins(viteEnv, isBuild),
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'ant-design-vue': ['ant-design-vue'],
            'ant-design-icons': ['@iconify-json/ant-design', '@iconify/vue'],
            'mockjs': ['mockjs'],
          },
          // entryFileNames: 'assets/[name].js',
          // chunkFileNames: 'assets/[name].js',
          // assetFileNames: 'assets/[name].[ext]',
        },
      },
    },
  }
})
